"""
url解码
import urllib
rawurl = "%E6%B2%B3%E6%BA%90"
url = urllib.parse.unquote(rawurl)
print url
"""
import urllib
import requests
import re
from requests.packages.urllib3.exceptions import InsecureRequestWarning

requests.packages.urllib3.disable_warnings(InsecureRequestWarning)  #不显示https Warning
headers = {"User-Agent":"Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:94.0) Gecko/20100101 Firefox/94.0"}
obj = re.compile(r'var vid="(?P<url>.*?)"',re.S) #提取m3u8的地址

#获得m3u8地址
url = 'https://91mjw.com/vplay/MTY0NDktMS0w.html'
r1 = requests.get(url,headers=headers)
m3u8_url = obj.search(r1.text).group("url")
m3u8_url = urllib.parse.unquote(m3u8_url)

ts_prefix = m3u8_url.replace("playlist.m3u8", "")
r1.close()

# #下载m3u8
# r2 = requests.get(m3u8_url,headers=headers)
# with open("video.m3u8",'wb') as f:
#     f.write(r2.content)

# r2.close()

# 解析m3u8
# 下载ts

with open('video.m3u8','r',encoding='utf-8') as f:
    
    for line in f:
        line = line.strip() #去掉空白和换行
        if line.startswith("#"): #如果以#开头,则不需要
            continue
        line = ts_prefix + line   
        
        #下载ts
        r3 = requests.get(line,headers=headers,verify=False,timeout=4)
        ts_name = line.split("/")[-1]
        f = open(".\\ts\\" + ts_name,'wb')
        f.write(r3.content)
        
        f.close()
        r3.close()
        
        print("done %s" %(ts_name))
    

